package com.aw.guiguzi.module.manager._user.presenters

import com.aw.baselib.base.AwCommonPresenter
import com.aw.baselib.net.callback.AwApiCallback
import com.aw.baselib.util.AwDataUtil
import com.aw.guiguzi.bean.BasePageRspBean
import com.aw.guiguzi.bean.UserInfoBean
import com.aw.guiguzi.module.manager._user.views.UserCreateView
import com.aw.guiguzi.net.observers.NetObCommon

/**
 * @author : hzw
 */
class UserCreatePresent(private val mView: UserCreateView.View) : AwCommonPresenter(),
    UserCreateView.Presenter {
    override fun createUser(bean: UserInfoBean?) {
        addIOSubscription(
            NetObCommon.createUser(bean),
            object : AwApiCallback<String>(mView, true, true) {
                override fun onSuccess(id: String) {
                    userRoleAssign(id)
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                    mView.showMsg(msg)
                }
            })
    }

    fun getUserList(username: String) {
        addIOSubscription<BasePageRspBean<UserInfoBean>>(
            NetObCommon.getUserList(1),
            object : AwApiCallback<BasePageRspBean<UserInfoBean>>(mView, true, true) {
                override fun onSuccess(result: BasePageRspBean<UserInfoBean>) {
                    val list = result.list
                    if (AwDataUtil.isEmpty(list)) {
                        return
                    }
                    for (bean in list!!) {
                        if (bean?.username == username) {
                            userRoleAssign(bean.id)
                            break
                        }
                    }
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                    mView.showMsg(msg)
                }
            })
    }

    override fun userRoleAssign(id: String?) {
        addIOSubscription(
            NetObCommon.userRoleAssign(id),
            object : AwApiCallback<Boolean>(mView, true, true) {
                override fun onSuccess(result: Boolean) {
                    mView.userRoleAssignSuccess()
                }

                override fun onFail(code: Int, msg: String) {
                    super.onFail(code, msg)
                    mView.showMsg(msg)
                    mView.userRoleAssignFail(code, msg)
                }
            })
    }
}